package cn.new7as.cas5s.ui.apply;


import static cn.new7as.cas5s.tool.util.Utils.CAMERA_A;

import android.Manifest;
import android.annotation.SuppressLint;

import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.text.InputFilter;
import android.view.View;
import android.widget.EditText;


import androidx.annotation.NonNull;
import androidx.lifecycle.Lifecycle;
import androidx.lifecycle.LifecycleObserver;
import androidx.lifecycle.OnLifecycleEvent;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.hjq.http.EasyHttp;
import com.hjq.http.listener.OnHttpListener;
import com.hjq.http.listener.OnUpdateListener;
import com.hjq.permissions.OnPermissionCallback;
import com.hjq.permissions.XXPermissions;
import com.lxj.xpopup.XPopup;
import com.lxj.xpopup.core.BasePopupView;
import com.lxj.xpopup.interfaces.OnSelectListener;


import java.io.File;
import java.util.List;

import cn.new7as.cas5s.ui.easy.netapi.PointApi;
import cn.new7as.cas5s.ui.slideshow.BaseActivity;
import cn.new7as.cas5s.R;
import cn.new7as.cas5s.anhjkfu.DatePop;
import cn.new7as.cas5s.anhjkfu.OnConfirmListener;
import cn.new7as.cas5s.tool.util.Utils;
import cn.new7as.cas5s.databinding.ActivityInfoThirdBinding;
import cn.new7as.cas5s.ui.easy.netapi.HttpData;
import cn.new7as.cas5s.ui.easy.netapi.GetBaseDataApi;
import cn.new7as.cas5s.ui.easy.netapi.OcrApi;
import cn.new7as.cas5s.ui.easy.netapi.SaveBaseDataApi;
import cn.new7as.cas5s.ui.easy.netapi.UpdateImageApi;


public class Info_ThirdActivity extends BaseActivity {
    public static final int ALBUM_A = 1212;
    protected String[] needPermissions = {Manifest.permission.CAMERA,};


    private String[] rl = new String[]{"Man", "Woman"};
    private String[] rlphotp = new String[]{"Camera", "Album"};
    private int imgtype;
    private long tstart;
    private int froncount;

    //  private int backcount;
    private int facecount;
    private int fronDuration;
    //   private int backDuration;
    private int faceDuration;
    private ActivityInfoThirdBinding binding;
    SaveBaseDataApi.Data3 data1;

    @SuppressLint("MissingPermission")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = ActivityInfoThirdBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());
        setop("Step3", new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Utils.go(Info_ThirdActivity.this, Info_SecondActivity.class);
                finish();
            }
        });
        data1 = new SaveBaseDataApi().new Data3();
        show();
        getBase();
        initV();
        Glide.with(Info_ThirdActivity.this).load(R.mipmap.frontside).into(binding.frontphotp);


    }

    @Override
    public void initV() {
        super.initV();
        binding.pancardidBa.setFilters(new InputFilter[] {new InputFilter.AllCaps()});

        setPoint(binding.aadhaaridBa, 1);
        setPoint(binding.pancardidBa, 2);
        setPoint(binding.nameBa, 3);
        setEtListener(binding.aadhaaridBa, binding.pancardidBa, binding.nameBa);
        binding.genderBa.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showbottom(1);
            }
        });

        binding.dateofbirthBa.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                bircount++;
                editstart = System.currentTimeMillis();
                BasePopupView s = new XPopup.Builder(Info_ThirdActivity.this).moveUpToKeyboard(false).enableDrag(true).isViewMode(true).isDestroyOnDismiss(true)

                        .asCustom(new DatePop(Info_ThirdActivity.this).setPopupCallback(new OnConfirmListener() {
                            @Override
                            public void onConfirm(String rscore) {
                                binding.dateofbirthBa.setText(rscore);
                                setTrue();
                            }

                            @Override
                            public void nextloan(String rscore) {

                            }
                        })).show();
                s.getLifecycle().addObserver(new LifecycleObserver() {
                    @OnLifecycleEvent(Lifecycle.Event.ON_STOP)
                    public void ondismiss() {
                        birDuration += (int) ((System.currentTimeMillis() - editstart) / 1000);

                    }
                });
            }
        });
        binding.frontphotp.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                imgtype = 0;
                froncount++;
                showPhoto2();
            }
        });
        binding.backphoto.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                imgtype = 1;
                //    backcount++;
                showPhoto2();
            }
        });
        binding.livephoto.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                imgtype = 9;
                facecount++;
                tstart = System.currentTimeMillis();
                if (XXPermissions.isGranted(Info_ThirdActivity.this, needPermissions)) {
                    Utils.getcameimg(Info_ThirdActivity.this, 1);
                } else XXPermissions.with(Info_ThirdActivity.this)

                        .permission(needPermissions)

                        .request(new OnPermissionCallback() {

                            @Override
                            public void onGranted(@NonNull List<String> permissions, boolean allGranted) {
                                Utils.getcameimg(Info_ThirdActivity.this, 1);
                            }

                            @Override
                            public void onDenied(@NonNull List<String> permissions, boolean doNotAskAgain) {

                            }
                        });
            }
        });
        binding.verifyme.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String nameBa = binding.nameBa.getText().toString();
                String pancardidBa = binding.pancardidBa.getText().toString();
                String aadhaaridBa = binding.aadhaaridBa.getText().toString();
                String dateofbirthBa = binding.dateofbirthBa.getText().toString();
                if (aadhaaridBa.length() != 12) {
                    toa(getString(R.string.aad_wrong));
                    return;
                }
                if (pancardidBa.length() != 10) {
                    toa(getString(R.string.pan_wrong));
                    return;
                }

                data1.aadhaarNo = aadhaaridBa;
                data1.dateOfbirth = dateofbirthBa;

                data1.panCardNo = pancardidBa;
                data1.fullName = nameBa;
                data1.gender = sta + "";
                show();
                EasyHttp.post(Info_ThirdActivity.this).api(new SaveBaseDataApi(getunique(), null, 4, null, data1, null)).request(new OnHttpListener<HttpData<Object>>() {
                    @Override
                    public void onHttpSuccess(@NonNull HttpData<Object> result) {
                        hide();
                        point(getunique());

                    }

                    @Override
                    public void onHttpFail(@NonNull Throwable throwable) {
                        deal(throwable);

                    }
                });
            }


        });
    }

    void ocra(int fron, String url) {

        EasyHttp.post(Info_ThirdActivity.this).api(new OcrApi(getunique(), fron, url)).request(new OnHttpListener<HttpData<Object>>() {
            @Override
            public void onHttpSuccess(@NonNull HttpData<Object> result) {
                hide();

                if (fron == 1) {
                    Glide.with(Info_ThirdActivity.this).load(url).thumbnail(0.1f).override(100, 100).diskCacheStrategy(DiskCacheStrategy.ALL).into(binding.frontphotp);
                    data1.cardFrontUrl = url;
                } else {
                    Glide.with(Info_ThirdActivity.this).load(url).into(binding.backphoto);
                    data1.cardBackUrl = url;
                }

            }

            @Override
            public void onHttpFail(@NonNull Throwable throwable) {
                deal(throwable);

            }
        });
    }


    long editstart;
    int aadcount;
    int aadDuration;

    int gencount;
    int genDuration;
    int pancount;
    int panDuration;

    int namecount;
    int nameDuration;
    int bircount;
    int birDuration;


    void setPoint(EditText editText, int type) {
        editText.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (hasFocus) {
                    switch (type) {
                        case 1:
                            aadcount++;
                            break;
                        case 2:
                            pancount++;
                            break;
                        case 3:
                            namecount++;
                            break;
                        case 4:
                            break;
                    }

                    editstart = System.currentTimeMillis();
                } else {
                    int i = (int) ((System.currentTimeMillis() - editstart) / 1000);

                    switch (type) {
                        case 1:
                            aadDuration += i;
                            break;
                        case 2:
                            panDuration += i;
                            break;
                        case 3:
                            nameDuration += i;
                            break;
                        case 4:

                            break;
                    }

                }
            }
        });
    }


    void getBase() {
        EasyHttp.post(Info_ThirdActivity.this).api(new GetBaseDataApi(getunique(), 4)).request(new OnHttpListener<HttpData<GetBaseDataApi.Data>>() {

            @Override
            public void onHttpSuccess(@NonNull HttpData<GetBaseDataApi.Data> result) {
                hide();
                if (result.getResult() != null) {
                    if (result.getResult() != null) {
                        binding.nameBa.setText(result.getResult().fullName);
                        binding.pancardidBa.setText(result.getResult().panCardNo);
                        binding.aadhaaridBa.setText(result.getResult().aadhaarNo);
                        binding.dateofbirthBa.setText(result.getResult().dateOfbirth);


                        Glide.with(getBaseContext()).load(result.getResult().cardFrontUrl).into(binding.frontphotp);
                        Glide.with(getBaseContext()).load(result.getResult().cardBackUrl).into(binding.backphoto);
                        Glide.with(getBaseContext()).load(result.getResult().faceUrl).into(binding.livephoto);
                        data1.cardFrontUrl = result.getResult().cardFrontUrl;
                        data1.cardBackUrl = result.getResult().cardBackUrl;
                        data1.faceUrl = result.getResult().faceUrl;

                        try {
                            binding.genderBa.setText(rl[Integer.parseInt(result.getResult().gender)]);
                            sta = Integer.parseInt(result.getResult().gender);
                        } catch (Exception ignored) {

                        }
                    }

                    setTrue();
                }
            }

            @Override
            public void onHttpFail(@NonNull Throwable throwable) {
                deal(throwable);

            }
        });
    }

    @Override
    public void setFalse() {
        super.setFalse();
        binding.verifyme.setEnabled(false);
    }

    int sta = -1;


    @Override
    public void setTrue() {
        super.setTrue();
        try {
            if (Utils.isStr(binding.nameBa, binding.aadhaaridBa, binding.pancardidBa) && Utils.isInt(sta) && !binding.dateofbirthBa.getText().toString().isEmpty() && (data1 != null && !data1.faceUrl.isEmpty() && !data1.cardFrontUrl.isEmpty()))
                binding.verifyme.setEnabled(true);
        }catch (Exception e){

        }

    }


    private int ba;

    @Override
    protected void onStop() {
        super.onStop();
        ba++;
    }


    private void point(String s) {
        long end = System.currentTimeMillis();
        PointApi.Point4Data pointData = new PointApi().new Point4Data();
        pointData.type = 4;

        pointData.basicpage_backend_num = ba;

        pointData.aadhaar_no_updatecount = aadcount;
        pointData.aadhaar_no_duration = aadDuration;

        pointData.gender_updatecount = gencount;
        pointData.gender_duration = genDuration;

        pointData.pan_num_updatecount = pancount;
        pointData.pan_num_duration = panDuration;

        pointData.fullname_updatecount = namecount;
        pointData.fullname_duration = nameDuration;

        pointData.birthday_updatecount = bircount;
        pointData.birthday_duration = birDuration;
        pointData.aadhaar_front_updatecount = froncount;
        pointData.aadhaar_front_duration = fronDuration;

        pointData.living_updatecount = facecount;
        pointData.living_duration = faceDuration;

        pointData.kycpage_stop_duration = (int) ((end - start) / 1000);
        pointData.frist_click_time = Utils.getdate(start);
        pointData.end_click_time = Utils.getdate(end);
        EasyHttp.post(this).api(new PointApi(s, pointData)).request(new OnHttpListener<HttpData<Object>>() {
            @Override
            public void onHttpSuccess(@NonNull HttpData<Object> result) {
                Utils.go(Info_ThirdActivity.this, Info_ForthActivity.class);
                finish();
                hide();
            }

            @Override
            public void onHttpFail(@NonNull Throwable throwable) {
                deal(throwable);
            }
        });

    }


    void showbottom(int type) {
        gencount++;
        editstart = System.currentTimeMillis();
        BasePopupView s = new XPopup.Builder(this).isDestroyOnDismiss(true)

                .asBottomList("Gender", rl, null, -1, new OnSelectListener() {
                    @Override
                    public void onSelect(int position, String text) {
                        switch (type) {
                            case 1:
                                binding.genderBa.setText(text);
                                sta = position;
                                break;

                        }
                        setTrue();

                    }
                }).show();
        s.getLifecycle().addObserver(new LifecycleObserver() {
            @OnLifecycleEvent(Lifecycle.Event.ON_STOP)
            public void ondismiss() {
                genDuration += (int) ((System.currentTimeMillis() - editstart) / 1000);

            }
        });
    }

    void showPhoto() {
        if (XXPermissions.isGranted(this, needPermissions)) {
            Utils.getcameimg(Info_ThirdActivity.this, 0);
        } else XXPermissions.with(Info_ThirdActivity.this)

                .permission(needPermissions)

                .request(new OnPermissionCallback() {

                    @Override
                    public void onGranted(@NonNull List<String> permissions, boolean allGranted) {
                        Utils.getcameimg(Info_ThirdActivity.this, 0);
                    }

                    @Override
                    public void onDenied(@NonNull List<String> permissions, boolean doNotAskAgain) {

                    }
                });


    }


    void showPhoto2() {

        tstart = System.currentTimeMillis();
        new XPopup.Builder(this).isDestroyOnDismiss(true).asBottomList("", rlphotp, null, -1, new OnSelectListener() {
            @Override
            public void onSelect(int position, String text) {
                if (position == 0) {
                    showPhoto();
                } else {
                    Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
                    intent.setType("image/*");
                    startActivityForResult(intent, ALBUM_A);
                }

            }
        }).show();


    }


    @SuppressLint("MissingSuperCall")
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {

        if (resultCode == RESULT_OK) {
            Bitmap bitmap;
            show();
            switch (requestCode) {

                case CAMERA_A:

                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                        bitmap = Utils.getBitmapFromUri(Info_ThirdActivity.this, Utils.getUri(Info_ThirdActivity.this));
                    } else {
                        bitmap = Utils.getBitmapFromUri(Info_ThirdActivity.this, Uri.fromFile(Utils.imgFile));
                    }

                    // binding.frontphotp.setImageBitmap(bitmap);
                    upload(Utils.saveBitmapFile(getBaseContext(), bitmap));
                    break;
                case ALBUM_A:
                    bitmap = Utils.getBitmapFromUri(Info_ThirdActivity.this, data.getData());
                    //  binding.frontphotp.setImageBitmap(bitmap);
                    upload(Utils.saveBitmapFile(getBaseContext(), bitmap));
                    break;
                default:
                    break;
            }
        }

    }

    void upload(File file) {
        EasyHttp.post(this).api(new UpdateImageApi(file)).request(new OnUpdateListener<HttpData<String>>() {
            @Override
            public void onUpdateProgressChange(int progress) {

            }

            @Override
            public void onUpdateSuccess(HttpData<String> result) {

                if (imgtype == 0) {
                    ocra(1, result.getResult());
                    fronDuration += (int) ((System.currentTimeMillis() - tstart) / 1000);
                } else if (imgtype == 1) {
                    ocra(2, result.getResult());
                    //   backDuration += (int) ((System.currentTimeMillis() - tstart) / 1000);
                } else if (imgtype == 9) {
                    hide();
                    faceDuration += (int) ((System.currentTimeMillis() - tstart) / 1000);
                    Glide.with(Info_ThirdActivity.this).load(result.getResult()).into(binding.livephoto);
                    data1.faceUrl = result.getResult();
                }
                setTrue();
            }

            @Override
            public void onUpdateFail(@NonNull Throwable throwable) {
                deal(throwable);
            }

        });

    }
}